import { User, Visitor, Role, FakeSuper } from './components/user';
import { defineStore } from 'pinia'
import { ElNotification } from 'element-plus';

export const UseLibraryState = defineStore('library', {
    state: () => {
        const user_str = localStorage.getItem('user')
        const user: User = user_str ? JSON.parse(user_str) : Visitor;
        console.info('Loading user data:', user)
        return {
            user,
            show_login: false,
            active_pane: 'index',
            fetch_changed: false,
        }
    },
    getters: {
        can_borrow(state) {
            return state.user.role == 'Reader'
        },
        is_manager(state) {
            return state.user.role?.toLowerCase().includes('manager')
        }
        ,
        is_reader(state) {
            return state.user.role?.toLocaleLowerCase().includes('reader')
        },
        is_super_manager(state) {
            return state.user.role == 'SuperManager'
        },
        can_manage_book(state) {
            return state.user?.role && (state.user.role == 'BookManager' || state.user.role == 'SuperManager')
        },
        can_manage_user(state) {
            return state.user?.role && (state.user.role == 'UserManager' || state.user.role == 'SuperManager')
        },
        is_login(state) {
            return state.user.token && state.user.token > 0
        },
        user_symbol(state) {
            switch (state.user.role) {
                case 'Visitor':
                    return '游客'
                case 'Reader':
                    return '读者'
                case 'BookManager':
                    return '书管'
                case 'UserManager':
                    return '读管'
                case 'SuperManager':
                    return '超管'
                default:
                    return '?'
            }
        },
        get_header(state) {
            if (state.user.token) {
                return {
                    'X-Token': state.user.token,
                    'X-UID': state.user.id,
                }
            } else {
                return {}
            }
        }
    },
    actions: {
        loggedIn(user: User) {
            this.user = user
            const user_str = JSON.stringify(user)
            localStorage.setItem('user', user_str)
            console.log('save user to localStorage:', user_str)
        },
        loggedOut() {
            localStorage.removeItem('user')
            this.user = Visitor
            this.active_pane = 'index'
            console.log('remove user from localStorage');
        },
        async check_login_state() {
            if (!this.user.token) {
                return
            }
            const api = '/api/user/check'
            const res = await fetch(api)
            if (!res.ok) {
                console.warn('User token is outdated!')
                this.user = Visitor
            } else {
                console.info('User token is valid!')
            }
        },
        change_fetch() {
            if(this.fetch_changed) return
            const fetch = window.fetch;
            window.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
                const options = {
                    ...init,
                    headers: {
                        ...this.get_header,
                        ...init?.headers,
                    }
                }
                // console.log('Fetch options:', options)
                //@ts-ignore
                const res = await fetch(input, options)
                if (res.status == 401) {
                    ElNotification.error({
                        message: '当前账户登录过期, 请重新登录!',
                        title: 'Error',
                        duration: 10000,
                    })
                    this.loggedOut()
                }
                else if (res.status == 403) {
                    ElNotification.error({
                        message: '当前账户无权进行此操作, 请切换账户!',
                        title: 'Error',
                        duration: 10000,
                    })
                }
                //  console.dir(res)
                return res
            }
            this.fetch_changed=true
        }
    }
})